/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * MS Access provider
 * @author Hung Cuong <nhc.hcmuns at gmail.com>
 */
public class MSAccessProvider {
    private Connection _Cnn;
    private Statement _Sttm;

    private static String _FullDbPath;
    public static void setFullDbPath(String value) {
        _FullDbPath = value;
    }

    public MSAccessProvider() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            Properties props = new Properties();
            props.put("charSet", "UTF8");

            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + _FullDbPath;

            _Cnn = DriverManager.getConnection(url, props);
            _Sttm = _Cnn.createStatement();

        } catch (Exception ex) {
            Logger.getLogger(ContactDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void connect() {
        try {
            Properties props = new Properties();
            props.put("charSet", "UTF8");

            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + _FullDbPath;
            
            _Cnn = DriverManager.getConnection(url, props);
            _Sttm = _Cnn.createStatement();

        } catch (SQLException ex) {
            Logger.getLogger(MSAccessProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void disconnect() {
        try {
            _Sttm.close();
            _Cnn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MSAccessProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void excuteNonQuery(String query) {
        try {
            _Sttm.execute(query); // execute non query
        } catch (SQLException ex) {
            Logger.getLogger(MSAccessProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ResultSet executeQuery(String query) {
        ResultSet rs = null;
        try {
            rs = _Sttm.executeQuery(query); // execute query (for SELECT)
            
        } catch (SQLException ex) {
            Logger.getLogger(MSAccessProvider.class.getName()).log(Level.SEVERE, null, ex);
        }

        return rs;
    }
}
